<template>
    <div>
        <div style="margin:20rem auto" v-for="(item,index) in data" :key="index">{{item}}</div>
        <input type="text" v-model="msg" class="wjhinput">
        <button @click="send()">发送</button>
    </div>
</template>
<script setup>
import {reactive,ref} from 'vue'
const ws= new WebSocket('ws://127.0.0.1:8540/test')
let data=reactive([])
let msg=ref('')
ws.onopen=()=>{
    // 打开WebSocket连接后立刻发送一条消息:
    ws.send(JSON.stringify({user:'jiahui',content:'123',type:'login',to:'all'}) ); 
}

ws.onmessage=(msg)=>{
    //获取所有信息展示在客户端
    console.log(msg)
    data.push(msg.data)
}

//客户端监控异常信息
ws.onerror=(error)=>{
    if(error){
        console.log(error)
    }
}

ws.onclose=()=>{
    console.log(`下线了`);
}
const send=()=>{
    ws.send(JSON.stringify({user:'jiahui',content:msg.value}))
}
</script>